# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "i康保.重疾（少儿版）"
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": ["0-5", "6-10", "11-15", "16-17"],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["100000", "300000"],
            # 保障期限
            "expire": ["1年"],
            # 交费类型
            "payType": ["年交"]

        }
        for v in product(plan["year"], plan["gender"], plan["money"], plan["expire"], plan["payType"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        gender: F
        coverageLevel: 02
        coverageAmount: 660000
        personAge: 12
        socialSecurity: Y
        '''
        data = Helper.perfectJson( params )
        data["gender"] = dt["gender"]
        data["coverageAmount"] = "220000" if dt["money"] == "100000" else "660000"
        data["personAge"] = str(int(dt["year"].split("-")[0]) + 1)
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload )
        if r.status_code == 200 and "totalPrem" in r.text:
            price  = Helper.decimalParse( r.json()["totalPrem"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
